/**
 * Created by zhangsong on 2019-01-18.
 */
const Parser = require('node-dbf').default;
const moment = require('moment');
const path = require('path');
const fs = require('fs');
const DbfDAO = require('../dao/dbf');
const config = require('../config/index');
const Cache = require('../common/cache');

const cache = new Cache({
  limit: 100,
  func: async (obj) => {
    await DbfDAO.createByMulti(obj);
    return null;
  },
});

function handle({ path }) {
  console.log(`开始读取${path}`);
  const name = path.substring(0, path.indexOf('.'));
  const date = moment(name).format('YYYY-MM-DD');
  return new Promise((resolve, reject) => {
    const parser = new Parser(path);

    parser.on('start', (p) => {
      console.log('dBase file parsing has started');
    });

    parser.on('header', function (obj) {
      console.log(obj);
    });
    // 遍历记录
    parser.on('record', function (obj) {
      cache.set({
        date,
        point: obj.pointid,
        temperature: obj.grid_code,
      });
    });

    parser.on('end', (p) => {
      cache.isDone().then(() => {
        resolve();
      });
    });

    parser.parse();
  });
};

(async function main() {
  const dirPath = config.input;
  const list = fs.readdirSync(dirPath);
  for (let i = 0; i < list.length; i++) {
    await handle({
      path: path.join(dirPath, list[i]),
    });
  }
})();
